<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传页</title>
    <script type="text/javascript" src="http://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div>
    <form id="imgform" method="post" action="/api/upload" enctype="multipart/form-data">
        <div>
            <input id="File1" type="file" name="myfile"/>
            <input type="submit">上传</input>
        </div>
    </form>
    <div id="result">

    </div>
</div>
<script>
    $('#imgform').submit(function (event) {
        event.preventDefault();
        var form = $(this);
        var formData = new FormData(this);
        $.ajax({
            type: form.attr('method'),
            url: form.attr('action'),
            data: formData,
            mimeType: "multipart/form-data",
            contentType: false,
            cache: false,
            processData: false,
            success: function (result, status, xhr) {
                if (xhr.status !== 200) {
                    alert("请求出错，状态码：" + xhr.status);
                    return
                }
                result = JSON.parse(result);
                if (result.code !== 0) {
                    alert("上传失败，状态码：" + result.code);
                    return
                }
                $('#result').text("上传成功，请稍后...");
                var timer = null;
                timer = setInterval(function () {
                    $.ajax({
                        type: 'get',
                        url: result.fileName,
                        cache: false,
                        processData: false,
                        success: function (imginfo, status, xhr) {
                            if (xhr.status !== 200) {
                                alert("请求出错，状态码：" + xhr.status);
                                return
                            }
                            if (imginfo.code !== 0) {
                                return
                            }
                            clearInterval(timer);
                            $('#result').html(
                                "<img src='"+ imginfo.imgurl+"' alt='图像加载失败' width='300'>"
                            )
                        }

                    })
                }, 500);
            },
            err: function (xhr, status, error) {
                alert("出错了：" + status);
            }
        })
    });

</script>
</body>
</html>
